package com.cuckoo.mall.thus.goodmultipledetail;


import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bgn.baseframe.base.BaseActivity;
import com.bgn.baseframe.utils.BaseStringUtil;
import com.bgn.baseframe.utils.ToastUtil;
import com.bgn.baseframe.utils.UiUtil;
import com.bgn.baseframe.utils.imageloader.ImageLoader;
import com.bgn.baseframe.utils.jsontool.GsonUtil;
import com.cuckoo.mall.R;
import com.cuckoo.mall.javabean.Product;
import com.cuckoo.mall.javabean.ProductAttribute;
import com.cuckoo.mall.thus.manager.UserInfoManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 作者：wl on 2018/4/ * 邮箱：wanglun@stosz.com
 */

@Route(path = "/mall/pickProductToOrderActivity", group = "mall")
public class PickProductToOrderActivity extends BaseActivity {

    @BindView(R.id.iv_image)
    ImageView ivImage;

    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.iv_close)
    ImageView ivClose;
    @BindView(R.id.recycle_pick)
    RecyclerView recyclePick;
    @BindView(R.id.tv_add_cart)
    TextView tvAddCart;
    /*shuju*/ List<ProductAttribute> goodPropertyItems = new ArrayList<>();
    private GoodPickAdapter pickAdapter;
    private EditText et_counts;
    private Product goodsInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setIsLoadTitleBar(false);
        setContentView(R.layout.activity_pick_good);
        ButterKnife.bind(this);
        controlKeyboardLayout(getmContainer(), tvAddCart);
        getStateBar().setBackgroundColor(R.color.transfullback);

        initData();
    }

    public void initData() {
        if (getIntent() != null && !TextUtils.isEmpty(getIntent().getStringExtra(JSON_STRING))) {
            goodsInfo = GsonUtil.fromJson(getIntent().getStringExtra(JSON_STRING), Product.class);
            if (goodsInfo != null) {
                initTopView();
                initRecrclyView();
            }
        } else {
            finish();
        }

    }

    private void initTopView() {
        ImageLoader.load(goodsInfo.getImage()).into(ivImage);

        tvPrice.setText(goodsInfo.getCurrency() + " " + BaseStringUtil.getPrioceFormatString(goodsInfo.getPrice()));
    }

    public void initRecrclyView() {
        goodPropertyItems.addAll(goodsInfo.getAttribute_list());
        pickAdapter = new GoodPickAdapter(goodPropertyItems);
        recyclePick.setAdapter(pickAdapter);
        recyclePick.setLayoutManager(new LinearLayoutManager(getActivity()));
        initFootView();
        pickAdapter.notifyDataSetChanged();
    }

    private void initFootView() {
        View view = UiUtil.inflate(R.layout.footview_pick_counts);
        ImageView tvAdd = (ImageView) view.findViewById(R.id.iv_add);
        ImageView tvMinus = (ImageView) view.findViewById(R.id.iv_minus);

        et_counts = (EditText) view.findViewById(R.id.et_counts);
        et_counts.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s)) {
                    if (s.toString().equals("0")) {
                        et_counts.setText("1");
                    } else if (Integer.parseInt(s.toString()) > 200) {
                        et_counts.setText("200");
                    }
                    //  editText.setSelection(editText.getText().toString().length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        tvMinus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String textString = et_counts.getText().toString();
                if (!TextUtils.isEmpty(textString)) {
                    int counts = Integer.parseInt(et_counts.getText().toString());
                    if (counts > 1) {
                        et_counts.setText(String.valueOf(counts - 1));
                    }
                }
            }
        });
        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String textString = et_counts.getText().toString();
                if (!TextUtils.isEmpty(textString)) {
                    int counts = Integer.parseInt(et_counts.getText().toString());
                    if (counts < 200) {
                        et_counts.setText(String.valueOf(counts + 1));
                    }
                }
            }
        });

        et_counts.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if ((TextUtils.isEmpty(et_counts.getText().toString()))) {
                        et_counts.setText("1");
                    }
                }
            }
        });
        pickAdapter.addFooterView(view);
    }

    public boolean checkData() {
        if (TextUtils.isEmpty(et_counts.getText().toString())) {
            ToastUtil.showInfo(getString(R.string.tip_quantity));
            return false;
        } else if (Integer.parseInt(et_counts.getText().toString()) <= 0) {
            ToastUtil.showInfo(getString(R.string.tip_quantity));
            return false;
        } else {
            for (ProductAttribute item : goodPropertyItems) {
                if (item.getValue() != null && item.getValue().size() > 0) {
                    if (TextUtils.isEmpty(item.getSelectedValue())) {
                        ToastUtil.showInfo(getString(R.string.tip_property) + item.getName());
                        return false;
                    }
                }
            }
            return true;
        }
    }

    @OnClick({R.id.iv_close, R.id.tv_add_cart})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_close:
                finish();
                break;
            case R.id.tv_add_cart:
//                if (goodsInfo != null && !TextUtils.isEmpty(et_counts.getText().toString())) {
//                    GoogleAnalyticsHelper.logAdd2Cart(this, goodsInfo.getProduct_id(), Integer.parseInt(et_counts.getText().toString()));
//                }
                if (checkData() && UserInfoManager.getInstance().checkTrunLogin()) {
                    if (isNetworkerConnectHint()) {
                        int num = Integer.parseInt(et_counts.getText().toString());
                        goodsInfo.setNumber(num);
                        goodsInfo.setAttribute_list(goodPropertyItems);
                        ARouter.getInstance().build("/mall/addOrderFromProductActivity").withString(DATASTRING, GsonUtil.toJson(goodsInfo)).navigation();
                    }
                }
                break;
        }
    }

    int srollhight = 0;

    public void controlKeyboardLayout(final View root, final View scrollToView) {
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect rect = new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int totalHight = root.getRootView().getHeight();
                int rootInvisibleHeight = totalHight - rect.bottom;
                //若不可视区域高度大于100，则键盘显示

                if (rootInvisibleHeight >= totalHight / 3) {
                    int[] location = new int[2];
                    //获取scrollToView在窗体的坐标
                    scrollToView.getLocationInWindow(location);
                    //计算root滚动高度，使scrollToView在可见区域
                    int srollHeight = (location[1] + scrollToView.getHeight()) - rect.bottom;
                    if (srollhight == 0) {
                        srollhight = srollHeight;
                        // + AppUtils.dip2px(mContext, 30);
                    }
                    root.scrollTo(0, srollhight);
                } else {
                    //键盘隐藏
                    root.scrollTo(0, 0);
                }
            }
        });
    }


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }
}
